const db = require('../../models/index');
const DAO = require('../../dao/sql-option-dao');
const { Op } = require("sequelize");
const logger = require('../../utils/logger-util');
const Article = db.article;
const Tags = db.tags;
const Sort = db.sort;
const ArticleTags = db.articleTags;
const Users = db.users;
const Likes = db.likes;
const Comments = db.comments;

// 文章-标签 多对多关系
Article.belongsToMany(Tags, {
    through: {
        model: ArticleTags,
    },
    foreignKey:'articleId'
});
Tags.belongsToMany(Article, {
    through: {
        model: ArticleTags,
    },
    foreignKey:'tagId'
});

// 文章-用户 点赞多对多关系
Users.belongsToMany(Article, {
    through: {
        model: Likes,
    },
    foreignKey:'userId'
});
Article.belongsToMany(Users, {
    through: {
        model: Likes,
    },
    foreignKey:'articleId'
});

// 文章-分类 一对一
Sort.hasOne(Article, {
    foreignKey: 'sortId',
    sourceKey: 'id'
});
Article.belongsTo(Sort, {
    foreignKey: 'sortId',
    sourceKey: 'id'
});

// 文章-评论 一对多关系
Article.hasMany(Comments, {
    foreignKey: 'articleId',
    sourceKey: 'id'
});
Comments.belongsTo(Article, {
    foreignKey: 'articleId',
    sourceKey: 'id'
});

// 创建文章
exports.create = async (req, res) => {
    try {
        const createInfo = req.body;
        // 查询所有标签
        let tags = await Tags.findAll({
            where: {
                id: createInfo.tags || []
            }
        });
        // 创建文章
        let newArticle = await Article.create(createInfo);
        newArticle.setTags(tags);
        res.sendResultAto(null, 200, '创建成功');
    } catch (e) {
        console.log(e)
    }
};

// 查询所有文章
exports.findAll = (req, res) => {
    const fAllInfo = req.body;
    fAllInfo.params.articleTitle ? fAllInfo.params.articleTitle = {
        [Op.substring]: `%${fAllInfo.params.articleTitle}%`
    } : fAllInfo.params.articleTitle = '';
    fAllInfo.raw = false;
    fAllInfo.include = [
        { model: Tags },
        { model: Sort },
        { model:Comments, order:[['createdAt', 'ASC']] }
    ];
    // fAllInfo.order = [['isTop', 'desc'], ['createdAt', 'desc']];
    DAO.list(Article, fAllInfo, data => {
        res.sendResult(data)
    });
};

// 查询单个文章
exports.findOne = (req, res) => {
    const fOneInfo = req.body;
    const queryInfo = {};
    queryInfo.params = {
        id: fOneInfo.id
    };
    queryInfo.raw = false;
    queryInfo.include = [
        { model: Tags },
        { model: Sort },
        { 
            model:Comments, 
            as:'comments', 
            order:[['createdAt', 'ASC']],
        },
        {
            model:Users, 
        }
    ];
    queryInfo.order = [['comments', 'createdAt', 'ASC']];
    DAO.findOne(Article, queryInfo, result => {
        // 查看详情文章时，将浏览量加1
        let updateViewInfo = {
            viewsCount: parseInt(result.data.viewsCount) + 1
        };
        // 当文章浏览量超过50时，为火热文章
        result.data.viewsCount > 50 && (updateViewInfo.isHot = true);
        // 更新文章浏览量
        DAO.update(Article, updateViewInfo, { id: result.data.id}, updateres => {
            DAO.findOne(Article, queryInfo, data => {
                res.sendResult(data);
            });
        });
    });
};

// ========================= 对文章进行点赞 =========================
// 更新点赞数量
async function updateLikesCount(modelData, model, updateField, type) {
    // 查询信息
    let updateParam = null;
    if(type==='add') {
        updateParam = {
            [updateField]: parseInt(modelData[updateField]) + 1
        };
    }else {
        updateParam = {
            [updateField]: parseInt(modelData[updateField]) - 1
        };
    }
    await model.update(updateParam, { where:{ id: modelData.id} });
};
// 点赞
exports.like = async (req, res) => {
    try {
        const likeInfo = req.body;
        let user = await Users.findOne({ where: { id: likeInfo.userId} });
        let article = await Article.findOne({ where: { id: likeInfo.articleId} });
        await updateLikesCount(user, Users, 'likesCount', 'add');
        await updateLikesCount(article, Article, 'likesCount', 'add');
        await user.setArticles(article);
        res.sendResultAto(null, 200, '修改成功');
    } catch (e) {
        console.log(e);
        logger.error(e);
        res.sendResultAto(null, 500, '服务器错误，请联系管理员！');
    };
};

// 取消对文章的点赞
exports.cancelLike = async (req, res) => {
    try {
        const cancelLikeInfo = req.body;
        let article = await Article.findOne({ where: { id: cancelLikeInfo.articleId} });
        let user = await Users.findOne({ where: { id: cancelLikeInfo.userId} });
        DAO.delete(Likes, { articleId: cancelLikeInfo.articleId }, async data => {
            await updateLikesCount(user, Users, 'likesCount', 'delete');
            await updateLikesCount(article, Article, 'likesCount', 'delete');
            res.sendResultAto(null, 200, '修改成功');
        });
    } catch (e) {
        console.log(e);
        logger.error(e);
        res.sendResultAto(null, 500, '服务器错误，请联系管理员！');
    };
};

// 更新文章信息
exports.update = async (req, res) => {
    try {
        const updateInfo = req.body;
        // updateInfo.sort_id = createInfo.sortId;
        let tags = await Tags.findAll({ where: { id: updateInfo.tags || [] } });
        Article.findByPk(updateInfo.id).then(row => {
            row.update(updateInfo);
            row.setTags(tags);
            res.sendResultAto(null, 200, '修改成功')
        })
    } catch (e) {
        console.log(e);
        logger.error(e);
        res.sendResultAto(null, 500, '服务器错误');
    };
};

// 删除文章信息
exports.delete = (req, res) => {
    const deleteInfo = req.body;
    // 先要删除有所关联的标签信息
    DAO.delete(ArticleTags, { articleId: deleteInfo.id }, tagData => {
        // 删除关联的所有评论
        Comments.destroy({ where: { articleId: deleteInfo.id} }).then(decomm => {
            // 删除当前文章信息
            DAO.delete(Article, { id: deleteInfo.id}, data => {
                res.sendResult(data)
            });
        });
    });
};

// 删除所有文章信息
exports.deleteAll = (req, res) => {
    DAO.deleteAll(Article, data => {
        res.sendResult(data)
    });
};


